package com.unisedu.weapp.repository;

import com.unisedu.weapp.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author hanbing
 */
@Repository
public class StudentRepository {

    private final JdbcTemplate jdbc;

    @Autowired
    public StudentRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    public void addUser(Student student){
        student.setStatus("0");
        String sql = "INSERT  INTO wx_student (name, gender, cardNumber, mobile, province, city, county, school, grade, email, className, status, openId) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
        List<String> items = student.getCheckbox();
        if(items.size()>0){
            items.forEach(item->{
                student.setClassName(item);
                jdbc.update(sql, student.getName(),student.getGender(),student.getCardNumber(),student.getMobile(),student.getProvince(),student.getCity(),student.getCounty(),student.getSchool(),student.getGrade(),student.getEmail(),student.getClassName(),student.getStatus(),student.getOpenId());
            });
        }
    }

    public List<String> getMyClasses(String openid) {
        String sql = "SELECT className from wx_student WHERE openId = ?";
        List<Map<String,Object>> result = jdbc.queryForList(sql, openid);
        List<String> list = new ArrayList<>(5);
        for(Map<String,Object> map: result){
            list.add(map.get("className").toString());
        }
        return list;
    }

    public String signUp(String className, String openid) {
        String sql = "SELECT * FROM wx_student WHERE openId = ?";
        List<Map<String,Object>> result = jdbc.queryForList(sql, openid);
        if(result.size() > 0){
            Map<String,Object> item = result.get(0);
            item.put("className", className);
            sql = "INSERT  INTO wx_student (name, gender, cardNumber, mobile, province, city, county, school, grade, email, className, status, openId) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
            jdbc.update(sql, item.get("name"),item.get("gender"),item.get("cardNumber"),item.get("mobile"),item.get("province"),item.get("city"),item.get("county"),item.get("school"),item.get("grade"),item.get("email"),item.get("className"),item.get("status"),item.get("openId"));
            return "报名成功";
        }else{
            return null;
        }


    }

    public boolean isSignUp(String openid) {
        String sql = "SELECT * FROM wx_student WHERE openId = ?";
        List<Map<String,Object>> result = jdbc.queryForList(sql, openid);
        return result.size() > 0;

    }
}
